package com.tem.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tem.content.entity.CmsType;
import com.api.manage.pojo.content.CmsTypeBean;
import com.tem.content.mapper.CmsTypeMapper;
import com.tem.content.service.ICmsTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈辉
 * @since 2023-11-07
 */
@Service
public class CmsTypeServiceImpl extends ServiceImpl<CmsTypeMapper, CmsType> implements ICmsTypeService {
    public List<CmsTypeBean> getTree(List<CmsTypeBean> list){
        return buildTree(list,0L);
    }
    public List<CmsTypeBean> getTree(Long sysBranchOfficeId){
        QueryWrapper<CmsType> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CmsType::getSysBranchOfficeId,sysBranchOfficeId);
        queryWrapper.orderByDesc("seq");
        List<CmsType> list = this.list(queryWrapper);
        if(list==null||list.size()<1)return null;
        List<CmsTypeBean> beans = new ArrayList<>();
        CmsTypeBean ctb = null;
        for (CmsType c:list){
            ctb = new CmsTypeBean();
            BeanUtils.copyProperties(c,ctb);
            beans.add(ctb);
        }
        //return this.buildTree(beans,0L);
        return this.buildTree1(beans);
    }
    /**
     * 新的递归方式
     * @param list
     * @param pid
     * @return
     */
    public List<CmsTypeBean> buildTree(List<CmsTypeBean> list, Long pid){
        List<CmsTypeBean> children = list.stream().filter(x -> x.getParentId().equals(pid)).collect(Collectors.toList());
        List<CmsTypeBean> subclass = list.stream().filter(x -> !x.getParentId().equals(pid)).collect(Collectors.toList());
        if(children.size() > 0){
            children.forEach(x -> {
                if(subclass.size() > 0){
                    buildTree(subclass,x.getCmsTypeId()).forEach(
                            y -> x.getChildren().add(y)
                    );
                }
            });
        }
        return children;
    }

    public List<CmsTypeBean> buildTree1(List<CmsTypeBean> list){
        List<CmsTypeBean> roots = new ArrayList<>();
        for(CmsTypeBean b:list){
            if(b.getParentId().longValue()==0l){
                roots.add(b);//根节点
                buildTree2(b,list);//子节点
            }
        }
        return roots;
    }
    public void buildTree2(CmsTypeBean parent , List<CmsTypeBean> list){
        for(CmsTypeBean b:list){
            if(b.getParentId().equals(parent.getCmsTypeId())){
                parent.getChildren().add(b);//子节点
                buildTree2(b,list);//递归继续找子节点
            }
        }
    }

}
